import os
import pylab as plt
from params import *

datasets = ['bkite','fsquare','livejournal', 'twitter']
lbls = ['Brightkite', 'Foursquare', 'LiveJournal', 'Twitter']

for dataset in datasets:
  tracefile = os.path.join(WORKDIR, 'gsn', 'results',dataset, '%s_node_locality.txt'%dataset)


  in_loc = {}
  in_deg = {}
  out_loc = {}
  out_deg = {}
  print tracefile
  for line in open(tracefile):
      user = int(line.split(' ')[0])
      outdeg, dout, indeg, din= map(float,line.split(' ')[1:])
      in_deg[user] = indeg
      if indeg > 0:
          in_loc[user] = din/indeg
      else:
          in_loc[user] = 0.0

      out_deg[user] = outdeg
      if outdeg > 0:
          out_loc[user] = dout/outdeg
      else:
          out_loc[user] = 0.0

  print "read %d users"%len(out_loc)

  out_locality = out_loc.values()
  in_locality = in_loc.values()
  print dataset
  avg_in_loc = sum(in_locality)/len(in_locality)
  avg_out_loc = sum(out_locality)/len(out_locality)
  print "Avg in locality ", avg_in_loc
  print "Avg out locality ", avg_out_loc
  directed = False
  if dataset == 'livejournal' or dataset == 'twitter':
    directed = True

  print dataset, directed

  pdf,bins,x = plt.hist(out_locality,bins=100,cumulative=False,normed=False)
  plt.close()

  c = [pdf[0]]
  for j in range(1,len(pdf)):
      t = c[j-1]
      c.append(t+pdf[j])

  total = c[-1]
  c = map(lambda x: 1.0*x/total, c)

  x1 = bins[:-1]
  y1 = c

  if directed:
      print 'directed!'
      pdf,bins,x = plt.hist(in_locality,bins=100,cumulative=False,normed=False)
      plt.close()

      c = [pdf[0]]
      for j in range(1,len(pdf)):
          t = c[j-1]
          c.append(t+pdf[j])

      total = c[-1]
      c = map(lambda x: 1.0*x/total, c)
      print 'total ', total
      x2 = bins[:-1]
      y2 = c


  plt.figure()
  plt.clf()
  plt.axes(FIG_AXES2)
  plt.plot(x1,y1,'k-')
  plt.xlabel('Node locality')
  plt.ylabel('CDF')
  plt.axis([0,1,0,1])
  if directed:
      plt.plot(x2,y2,'k--')
      plt.legend(['Out-locality', 'In-locality'],numpoints=1,
              loc='upper left')

  plt.grid(True)
  plt.savefig('%s_locality.pdf'%dataset)
  plt.close()
